const exec = require('../db/mysql');
const ensureIn = require('../utils/ensureIn');
const { defaultCover } = require('../conf/assets');

async function getPostsList(page, size) {
  const sql = `SELECT postId, cover, title, summary, modifyDatetime, author, views, collections FROM posts ORDER BY publishDatetime LIMIT ${size * (page - 1)},${size};`;
  const res = await exec(sql);

  return res;
}

async function updatePost(postId, postData) {
  const { title, cover, summary, content, modifyDatetime, author } = postData;
  const sql = `UPDATE posts SET
    title=${ensureIn(title)},
    cover=${ensureIn(cover || defaultCover)},
    summary=${ensureIn(summary)},
    content=${ensureIn(content)},
    modifyDatetime=${Date.now()}
    WHERE postId=${postId} AND author=${ensureIn(author)}`;
  const res = await exec(sql);

  return res;
}

async function newPost(postData) {
  const { postId, title, cover, summary, content, modifyDatetime, author } = postData;
  const currentTimestamp = Date.now();

  const sql = `INSERT INTO posts(postId, title, cover, summary, content, modifyDatetime, publishDatetime, author)
    values(
      ${postId},
      ${ensureIn(title)},
      ${ensureIn(cover || defaultCover)},
      ${ensureIn(summary)},
      ${ensureIn(content)},
      ${currentTimestamp},
      ${currentTimestamp},
      ${ensureIn(author)}
    )`;
  const res = await exec(sql);

  return res;
}

async function deletePost(postId, author) {

  const sql = `DELETE FROM posts WHERE postId=${postId} AND author=${ensureIn(author)}`;
  const res = await exec(sql);

  return res;
}

module.exports = {
  getPostsList,
  updatePost,
  newPost,
  deletePost,
}
